<template>
  <div class="vb-approve-form ">
    <div class="submit-person">
      <span>提交人：{{ staffName }}</span>
    </div>
    <div class="submit-form-process">
      <div class="form-el-form">
        <el-form ref="form" :model="form" label-width="120px">
          <div
            v-for="(originItem, originIndex) in originData"
            :key="originIndex"
            class="form_box"
          >
            <el-form-item
              v-for="(item, index) in getOriginItem(originItem)"
              :key="index"
              :prop="item.vModel"
              :label="handleLabel(item)"
            >
              <el-input
                v-model="form[item.vModel]"
                readonly
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="form-process">
        <div class="process-box">
          <div style="font-size: 16px;color: #3a3a3a;line-height: 22px;margin-bottom: 10px;">
            流程
          </div>
          <div class="process-start">
            <div style="display: flex">
              <div style="width: 20px">
                <div class="circular" />
                <div class="strip" />
              </div>
              <div>
                <div>发起申请</div>
                <div>{{ staffName }}</div>
              </div>
            </div>
          </div>
          <div
            v-for="(item, index) in linkData.links"
            :key="index"
            :class="{
              'process-start': true,
              'process-end': index === linkData.links.length - 1,
            }"
          >
            <div style="display: flex">
              <div style="width: 20px">
                <div class="circular" />
                <div class="strip" :style="handleStrip(item, index)" />
              </div>
              <div class="approve-header">
                <div v-if="item.userType === 'approver'">
                  <span v-if="kitValue == 99">接收人</span>
                  <span v-else>审批人</span>
                </div>
                <div v-else>办理人</div>
                <div class="select-number">
                  {{ handleSelectNumber(item, index) }}
                </div>
              </div>
              <div
                v-if="item.approvalMemberType !== 'optional'"
                class="approve-alreadySelect"
              >
                <div
                  v-for="(i, index1) in item.members"
                  :key="index1"
                  class="selected-member"
                >
                  <img v-if="i.avatar" class="member-img" :src="i.avatar">
                  <img
                    v-else
                    class="member-img"
                    src="@/assets/approval/default.png"
                  >
                  <div class="member-name">{{ i.staffName }}</div>
                </div>
              </div>
              <div class="approve-list">
                <div
                  v-for="i in selectedList[`approve${index}`]"
                  :key="i.staffId"
                >
                  <div class="selected-member">
                    <img v-if="i.avatar" class="member-img" :src="i.avatar">
                    <img
                      v-else
                      class="member-img"
                      src="@/assets/approval/default.png"
                    >
                    <div
                      class="member-delete"
                      @click="deleteMember(i, `approve${index}`)"
                    >
                      -
                    </div>
                    <div class="member-name">{{ i.staffName }}</div>
                  </div>
                </div>
              </div>
              <div
                v-if="item.approvalMemberType === 'optional'"
                class="member-plus"
                @click="selectApprove(index)"
              >
                <img
                  style="width: 30px; height: 30px"
                  src="@/assets/approval/join.svg"
                >
              </div>
            </div>
          </div>
          <div class="process-start">
            <div style="display: flex">
              <div style="width: 20px">
                <div class="circular" />
              </div>
              <div style="width: 74px">抄送人</div>
              <div class="copy-surround">
                <div class="copy-alreadySelect">
                  <div
                    v-for="(item, index) in copyLinkList"
                    :key="index"
                    class="selected-member"
                  >
                    <img
                      v-if="item.avatar"
                      class="member-img"
                      :src="item.avatar"
                    >
                    <img
                      v-else
                      class="member-img"
                      src="@/assets/approval/default.png"
                    >
                    <div class="member-name">{{ item.staffName }}</div>
                  </div>
                </div>
                <div class="copy-list">
                  <div v-for="i in selectedList.copy" :key="i.staffId">
                    <div class="selected-member">
                      <img v-if="i.avatar" class="member-img" :src="i.avatar">
                      <img
                        v-else
                        class="member-img"
                        src="@/assets/approval/default.png"
                      >
                      <div class="member-delete" @click="deleteMember(i, 'copy')">
                        -
                      </div>
                      <div class="member-name">{{ i.staffName }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div
                v-if="userOptional"
                style="cursor: pointer; position: absolute; right: 0"
                @click="selectCopy"
              >
                <img
                  style="width: 30px; height: 30px"
                  src="@/assets/approval/join.svg"
                >
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="button-box">
      <el-button
        class="submit-button"
        size="medium"
        @click="handleClose()"
      >取消</el-button>
      <el-button
        class="submit-button"
        :loading="submitLoading"
        type="primary"
        size="medium"
        @click="submitFormData('add')"
      >提交</el-button>
    </div>
    <userDialog
      v-if="copyVisible"
      :copy-visible="copyVisible"
      :company-id="companyId"
      @showCopyModal="showCopyModal"
    />
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import userDialog from './userDialog'
import { getApproveLinks, getApproveDetail, addApprove } from '@/api/approve'
import { mapFormData } from '@/utils/approve'
export default {
  components: {
    userDialog
  },
  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      }

    },
    staffName: {
      type: String,
      default: ''
    },
    modelId: {
      type: String,
      default: ''
    },
    companyId: {
      type: String,
      default: ''
    },
    dataId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      originData: [],
      fields: [],
      linkData: {},
      copyLinkList: [],
      userOptional: '',
      copyVisible: false,
      form: {},
      submitLoading: false,
      dept: {},
      kitValue: ''
    }
  },
  computed: {
    ...mapState({
      selectedList: (state) => state.user.selectedList,
      status: (state) => state.user.status
    })
  },
  watch: {
    linkData(val) {
      this.copyLinkList = val.copyLink.members
      this.userOptional = val.copyLink.userOptional
    }
  },
  async mounted() {
    const mapForm = {}
    this.form = { ...this.form, ...mapForm }
    // 获取老平台的
    await this.getApplyData()
    await this.getLinks()
  },
  methods: {
    ...mapMutations('user', [
      'setCheckedList',
      'setStatus',
      'clearSelectedList',
      'setSelectedList',
      'setMaxNum'
    ]),
    selectApprove(index) {
      this.setStatus(`approve${index}`)
      this.copyVisible = true
    },
    selectCopy() {
      this.setStatus('copy')
      this.copyVisible = true
    },
    showCopyModal() {
      this.copyVisible = !this.copyVisible
      const getDept = ''
      // if (this.status.slice(0, 4) === "dept") {
      //   this.selectedList[`dept${this.dept.vModel}`]?.forEach((item) => {
      //     getDept += item?.name ? item.name + "/" : item.staffName + "/";
      //   });
      //   if (!this.copyVisible) {
      //     (this.form[`${this.dept.vModel}`] = getDept?.slice(
      //       0,
      //       getDept.length - 1
      //     )),
      //       this.setMaxNum(0);
      //   }
      // }
    },
    getOriginItem(item) {
      return Object.prototype.hasOwnProperty.call(item, 'children')
        ? item.children
        : [item]
    },
    getApplyData() {
      getApproveDetail({
        modelId: this.modelId
      }).then(res => {
        if (res.code === 0) {
          this.kitValue = res.data.kitValue
          this.originData = res.data.formData.fields
          const fields = res.data.formData.fields.map((item) => {
            if (item.children) {
              item.children.forEach((i) => (i.isKit = item.isKit))
              return item.children
            } else {
              return item
            }
          })
          this.fields = this.flatten(fields)
          // 设置form
          this.form = mapFormData(this.data, this.fields)
          console.log('this.form:', this.form, this.data, this.fields)
          this.$emit('load')
        } else {
          this.$message.error(res.msg)
          this.$emit('load')
        }
      }).catch(ex => {
        this.$emit('load')
      })
    },
    getLinks() {
      const params = {
        companyId: this.companyId,
        modelId: this.modelId
      }
      getApproveLinks(params).then(res => {
        console.log('resssssss:', res)
        if (res.code === 0) {
          this.linkData = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    flatten(arr) {
      // 数组扁平化
      let res = []
      arr.map((item) => {
        if (Array.isArray(item)) {
          res = res.concat(this.flatten(item))
        } else {
          res.push(item)
        }
      })
      return res
    },
    handleLabel(item) {
      if (item.tagIcon === 'upload') return ''
      if (item.tagIcon === 'interviewInfo') return ''
      if (item.tagIcon === 'interviewInfos') return ''
      if (item.tagIcon === 'interviewInfoss') return ''
      if (item.tagIcon === 'interviewInfosss') return ''
      if (item.tagIcon === 'itemInfos') return ''
      if (item.tagIcon === 'ApplicationData') return ''
      if (
        item.tagIcon === 'switch' &&
        this.kitValue === 0 &&
        item.isKit === 0 &&
        item.label === '自动抄送转交人' &&
        !this.switchFlag
      ) { return '' }
      if (
        item.tagIcon === 'dept' &&
        this.kitValue === 0 &&
        item.isKit === 0 &&
        item.label === '接收人' &&
        !this.switchFlag
      ) { return '' }
      return item.label
    },
    handleStrip(item, index) {
      const length = (this.selectedList[`approve${index}`] ? this.selectedList[`approve${index}`].length : 0) || (item.members ? item.members.length : 0) || 0
      if (length === 0) {
        return
      } else {
        return {
          height:
            length < 6 ? `80px` : `${Math.ceil(length / 5 - 1) * 45 + 80}px`
        }
      }
    },
    handleSelectNumber(item, index) {
      // 处理是几人依次审批
      const length = (this.selectedList[`approve${index}`] ? this.selectedList[`approve${index}`].length : 0) || (item.members ? item.members.length : 0)
      return length > 0
        ? item.userType === 'approver'
          ? `${length}人依次审批`
          : `${length}人依次办理`
        : ''
    },
    deleteMember(item, number) {
      this.setCheckedList({
        data: item,
        status: true,
        number
      })
      this.$forceUpdate()
    },
    submitFormData(action) {
      const formData = { ...this.form }
      const links = this.linkData.links.map((item, index) => {
        if (item.approvalMemberType === 'optional') {
          return { ...item, members: this.selectedList[`approve${index}`] }
        } else {
          return item
        }
      })
      const copyLink = {
        members:
          this.linkData.copyLink.members.length > 0
            ? this.selectedList['copy'].concat(this.linkData.copyLink.members)
            : this.selectedList['copy']
      }
      if (action === 'add') this.submitLoading = true
      this.$refs.form.validate((validate) => {
        if (!validate) return false
        const data = {
          companyId: this.companyId,
          draftFlag: action === 'save' ? '0' : '1',
          fieldsStr: JSON.stringify(formData),
          modelId: this.modelId,
          platformModuleId: this.dataId,
          // instanceId: this.againSubmitFlag ? "" : this.instanceId || "",
          copyLink: this.selectedList['copy'] ? copyLink : this.linkData.copyLink,
          links
        }
        addApprove(data).then(res => {
          if (res.code === 0) {
            if (action === 'save') {
              this.$message.success('保存成功！')
              this.$emit('close', res)
            } else {
              this.$message.success('提交成功！')
              console.log('提交成功！:', res)
              this.$emit('close', res)
            }
            this.setCheckedList({})
            this.setStatus('')
            this.clearSelectedList({})
            this.submitLoading = false
          } else {
            this.$message.error(res.msg)
            this.submitLoading = false
          }
        }).catch(ex => {
          this.$message.error(ex.message)
          this.submitLoading = false
        })
      })
    },
    handleClose() {
      this.$emit('close')
      this.setCheckedList({})
      this.setStatus('')
      this.clearSelectedList({})
      this.$refs.form.resetFields()
    }
  }

}
</script>

<style lang="scss">
.vb-approve-form {
  display: flex;
  flex-direction: column;
  .submit-form-process{
    display: flex;
    background: #f9f9f9;
padding: 0 10px
  }
  .form-process{
    flex: 1;
    margin: 0 10px;
    padding-top:20px

  }
  .form-el-form{
    flex: 1;
margin: 0 10px
  }
  .form_box {
    -webkit-box-shadow: 0rem 0rem 0rem 0rem #f2f3f5;
    box-shadow: 0rem 0rem 0rem 0rem #f2f3f5;
    background-color: #ffffff;
    padding: 10px 10px;
    margin-bottom: 14px;
    border-radius: 8px;
  }
  .annex-box {
    width: 372px;
    padding: 14px;
    background: #ffffff;
    border-radius: 0rem;
    box-shadow: 0rem 0rem 0rem 0rem #f2f3f5;
    margin: 0 auto;
  }
  .interviewInfo-box {
    width: 372px;
    background: #ffffff;
    border-radius: 0rem;
    box-shadow: 0rem 0rem 0rem 0rem #f2f3f5;
    margin: 0 auto;
  }
  .submit-person {
    height: 49px;
    font-size: 14px;
    font-family: PingFangSC, PingFangSC-Medium;
    font-weight: 500;
    color: #333333;
    line-height: 24px;
    padding: 14px;
    background: #ffffff;
    box-shadow: 0px 2px 4px 0px #f2f3f5;
    display: flex;
    justify-content: space-between;
  }
  .button-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 30px;
    height: 60px;
  }
  .draft-button {
    width: 150px;
    height: 44px;
    background: #ffffff;
    border: 1px solid #666666;
    border-radius: 8px;
    font-size: 16px;
    font-family: PingFangSC, PingFangSC-Regular;
    font-weight: 400;
    text-align: center;
    color: #3a3a3a;
    line-height: 16px;
    margin-right: 10px;
  }

  .process-box {

    background: #ffffff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0px 2px 4px 0px #f2f3f5;
    border-radius: 10px;
    height: auto;
  }
  // .process-end {
  //   height: 40px !important;
  // }
  .process-start {
    display: flex;
    // height: 80px;
    justify-content: space-between;
    position: relative;
  }
  .process-arrow {
    width: 6px;
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    top: 43px;
    left: 16px;
    margin-top: 4px;
  }
  .process-arrow :first-child {
    width: 2px;
    height: 24px;
    background: #00ca7b;
  }
  .process-arrow :last-child {
    width: 0;
    height: 0;
    border-right: 3px solid transparent;
    border-left: 3px solid transparent;
    border-top: 4px solid #00ca7b;
  }
  .a-step-box {
    display: flex;
    flex-wrap: wrap;
    align-items: baseline;
    text-align: center;
  }
  .copy-box {
    width: 372px;
    background: #ffffff;
    padding: 14px;
    border-radius: 8px;
    margin: 14px auto;
    box-shadow: 0px 2px 4px 0px #f2f3f5;
  }
  .copy-list {
    // display: flex;
    // // height: 40px;
    // position: relative;

    display: flex;
    // flex-direction: row-reverse;
    flex-wrap: wrap;
    /* align-items: baseline; */
    text-align: center;
    max-width: 208px;
    // height: auto;
    margin-left: 4px;
  }
  .selected-member {
    display: flex;
    flex-direction: column;
    // align-items: center;
    width: 40px;
    height: 60px;
    position: relative;
    text-align: center;
  }
  .member-img {
    width: 30px;
    height: 30px;
    margin-right: 8px;
  }
  .member-delete {
    color: white;
    background: red;
    border-radius: 14px;
    width: 14px;
    height: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: -7.5px;
    left: 22px;
    cursor: pointer;
  }
  .circular {
    width: 10px;
    height: 10px;
    background-color: #d9d9d9;
    border-radius: 50%;
    // margin-top: 5px;
  }
  .circular1 {
    width: 10px;
    height: 10px;
    background-color: #d9d9d9;
    border-radius: 50%;
    // margin-top: 5px;
  }
  .strip {
    width: 1px;
    height: 80px;
    margin-left: 5px;
    background-color: #d9d9d9;
  }
  .member-bg {
    width: 30px;
    height: 30px;
    background: #1584ff;
    border-radius: 0.21rem;
    font-size: 0.32rem;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #ffffff;
    line-height: 30px;
    text-align: center;
    margin-right: 8px;
    position: absolute;
    right: 0px;
  }
  .approve-list {
    display: flex;
    // flex-direction: row-reverse;
    flex-wrap: wrap;
    /* align-items: baseline; */
    text-align: center;
    max-width: 208px;
    // height: auto;
    margin-left: 4px;
  }
  // .member-img {
  //   width: 15px;
  //   height: 15px;
  //   margin-right: 8px;
  // }
  .member-name {
    /* width: 0.8rem; */
    width: 36px;
    height: 25px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
    line-height: 25px;
    text-align: center;
  }
  .member-plus {
    /* width: 1.07rem;
  height: 1.07rem;
  background: rgb(255, 255, 255); */
    /* border: 1px solid rgb(196, 199, 213); */
    border-radius: 4px;
    font-size: 1.07rem;
    /* margin-right: 8px; */
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 0;
  }
  .staffNameBox {
    width: 30px;
    height: 30px;
    background: #1584ff;
    color: white;
    text-align: center;
    line-height: 30px;
    border-radius: 4px;
    font-size: 12px;
  }
  .copy-alreadySelect {
    margin-left: 4px;
    max-width: 208px;
    display: flex;
    // flex-direction: row-reverse;
  }
  .approve-alreadySelect {
    margin-left: 4px;
    max-width: 208px;
    display: flex;
    flex-wrap: wrap;
    // flex-direction: row-reverse;
  }
  .approve-header {
    display: flex;
    flex-direction: column;
    max-width: 74px;
    width: 74px;
  }
  .select-number {
    height: 17px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #888888;
    line-height: 17px;
  }
  .copy-surround {
    display: flex;
    flex-direction: column;
  }
  .el-form {

  box-shadow: 0rem 0rem 0rem 0rem #f2f3f5;
  padding: 0px;
    padding-top: 20px;
}
}

</style>
